<!--
 * @Author: your name
 * @Date: 2022-01-17 22:08:12
 * @LastEditTime: 2022-02-22 17:33:17
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue-element-admin\src\views\crm\Linkman.vue
-->
<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="addShow()"
        >添加客户</el-button
      > -->
    </div>
    <!-- <el-dropdown
      v-loading="transferData.multipleSelectionLoading"
      split-button
      style="margin-left: 30px"
    >
      更多操作
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item @click.native="manyChange"
          ><i class="el-icon-thumb"></i>批量取出</el-dropdown-item
        >
      </el-dropdown-menu>
    </el-dropdown> -->
    <TableGeneral
      :tableData="tableData"
      :tableColumn="tableColumn"
      :loading="tableLoading"
      :tableConfig="{ stripe: true }"
      @refresh="tableLoad"
      @search="search"
      @expandChange="expandChange"
      :slotArray="['联系人']"
      ref="general"
    >
      <div slot="nickName" slot-scope="{ scopeRow }">
        <span>{{
          `${scopeRow.nickName}${
            scopeRow.realName ? "(" + scopeRow.realName + ")" : ""
          }`
        }}</span>
      </div>

      <!-- <div slot="custom_level" slot-scope="{ scopeRow }">
        <span v-show="scopeRow.custom_level == 'A'">A(重点客户)</span>
        <span v-show="scopeRow.custom_level == 'B'">B(普通客户)</span>
        <span v-show="scopeRow.custom_level == 'C'">C(非优先客户)</span>
      </div> -->
      <div slot="star_num" slot-scope="{ scopeRow }" class="starNum">
        <template v-if="scopeRow.star_num">
          <i
            style="color: #ece91f"
            class="el-icon-star-on"
            v-for="index of scopeRow.star_num"
            :key="index"
          ></i>
        </template>
      </div>

      <div slot="联系人" slot-scope="{ scopeRow }" class="tableGeneral">
        <TableGeneral
          style="width: 100%"
          :gridData="true"
          :tableData="
            expandedRowsId.hasOwnProperty(scopeRow.id)
              ? expandedRowsId[scopeRow.id]
              : []
          "
          :tableColumn="gridData.gridDataColumn"
          :loading="!expandedRowsId.hasOwnProperty(scopeRow.id)"
          :tableConfig="{ stripe: true }"
        >
          <div slot="nickName" slot-scope="{ scopeRow }">
            <span>{{
              `${scopeRow.nickName}${
                scopeRow.realName ? "(" + scopeRow.realName + ")" : ""
              }`
            }}</span>
          </div>
          <div slot="crm_customer_id" slot-scope="{ scopeRow }">
            <div
              v-if="scopeRow.crm_customer_id"
              style="display: flex; flex-wrap: wrap"
            >
              <el-tag
                v-for="(item, index) in scopeRow.crm_customer_id.split(',')"
                :key="index"
                style="margin-left: 5px"
                >{{ item }}</el-tag
              >
            </div>
          </div>
          <div slot="customer_company_name" slot-scope="{ scopeRow }">
            <div
              v-if="scopeRow.customer_company_name"
              style="display: flex; flex-wrap: wrap"
            >
              <el-tag
                v-for="(item, index) in scopeRow.customer_company_name.split(
                  ','
                )"
                :key="index"
                style="margin-left: 5px"
                >{{ item }}</el-tag
              >
            </div>
          </div>
          <div slot="sex" slot-scope="{ scopeRow }">
            <span v-show="scopeRow.sex == 1">男</span>
            <span v-show="scopeRow.sex == 0">女</span>
          </div>
        </TableGeneral>
      </div>
      <div slot="operation" slot-scope="{ scopeRow }">
        <el-button type="text" size="small" @click="edit(scopeRow)">
          编辑
        </el-button>

        <el-button type="text" size="small" @click="followUp(scopeRow.id)">
          跟进情况
        </el-button>
        <!-- <template> -->

        <el-button type="text" size="small" @click="transfer(scopeRow)">
          取出
        </el-button>
        <!-- <el-popconfirm title="确定要取出吗" @confirm="takeOut(scopeRow)">
          <el-button type="text" size="small"  slot="reference"  style="margin-left: 10px"> 取出 </el-button>
        </el-popconfirm> -->
        <el-popconfirm title="确定要删除吗" @confirm="delOne(scopeRow.id)">
          <!-- <div> -->
          <el-button
            slot="reference"
            type="text"
            size="small"
            style="margin-left: 10px"
            >删除</el-button
          >
        </el-popconfirm>
      </div>
    </TableGeneral>

    <div class="pagination">
      <el-pagination
        background
        layout="sizes,total,prev, pager, next"
        :page-size="config.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="sizeChange"
        :total="tableCount"
        @current-change="currentChange"
      >
      </el-pagination>
    </div>
    <!-- 添加联系人 -->
    <el-dialog
      :title="`${edit_id ? '编辑' : '添加'}客户`"
      :visible.sync="dialogFormVisible"
      top="5vh"
      @closed="closed"
    >
      <div class="dialogCenter">
        <el-form
          :model="form"
          ref="form"
          :rules="rules"
          v-loading="formLoading"
        >
          <el-form-item
            label="公司名称"
            :label-width="formLabelWidth"
            prop="company_name"
          >
            <!-- <el-input v-model="form.company_name" autocomplete="off"></el-input> -->
            <div class="company_name-part">
            <el-input style="flex:1" v-model="form.company_name" autocomplete="off"></el-input>
           <el-input  style="width:200px;margin-left:20px" v-model="form.industry" autocomplete="off">   <template slot="prepend">行业</template></el-input>
          </div>
          </el-form-item>
          <el-form-item
            label="成立日期"
            :label-width="formLabelWidth"
            prop="establish_date"
          >
            <el-input v-model="form.establish_date" autocomplete="off"></el-input>
          </el-form-item>
         <el-form-item
            label="注册地址"
            :label-width="formLabelWidth"
            prop="address"
          >
            <el-input v-model="form.address" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="联系人"
            :label-width="formLabelWidth"
            prop="linkman_id"
          >
            <div class="linkman-part">
              <el-popover
                placement="right"
                width="700"
                trigger="click"
                @show="linkmanListLoad"
              >
                <div class="gridDataTable" v-loading="gridData.loading">
                  <TableGeneral
                    ref="gridData"
                    v-if="gridData.data.length > 0"
                    :gridData="true"
                    :tableData="gridData.data"
                    :tableColumn="gridData.gridDataColumn"
                    :tableConfig="{ stripe: true }"
                  >
                    <div slot="nickName" slot-scope="{ scopeRow }">
                      <span>{{
                        `${scopeRow.nickName}${
                          scopeRow.realName ? "(" + scopeRow.realName + ")" : ""
                        }`
                      }}</span>
                    </div>
                    <div slot="crm_customer_id" slot-scope="{ scopeRow }">
                      <div
                        v-if="scopeRow.crm_customer_id"
                        style="display: flex; flex-wrap: wrap"
                      >
                        <el-tag
                          v-for="(
                            item, index
                          ) in scopeRow.crm_customer_id.split(',')"
                          :key="index"
                          style="margin-left: 5px"
                          >{{ item }}</el-tag
                        >
                      </div>
                    </div>
                    <div slot="customer_company_name" slot-scope="{ scopeRow }">
                      <div
                        v-if="scopeRow.customer_company_name"
                        style="display: flex; flex-wrap: wrap"
                      >
                        <el-tag
                          v-for="(
                            item, index
                          ) in scopeRow.customer_company_name.split(',')"
                          :key="index"
                          style="margin-left: 5px"
                          >{{ item }}</el-tag
                        >
                      </div>
                    </div>
                    <div slot="sex" slot-scope="{ scopeRow }">
                      <span v-show="scopeRow.sex == 1">男</span>
                      <span v-show="scopeRow.sex == 0">女</span>
                    </div>
                  </TableGeneral>

                  <el-empty description="暂无数据" v-else></el-empty>
                </div>

                <el-badge
                  :value="linkmanSelList.length"
                  class="item"
                  slot="reference"
                >
                  <el-button size="small">当前联系人</el-button>
                </el-badge>
              </el-popover>

              <el-button
                class="button-new-tag"
                size="small"
                @click="showInput"
                v-loading="gridData.loading"
                >+ 联系人</el-button
              >
            </div>
          </el-form-item>

          <!-- <el-form-item
            label="行业"
            :label-width="formLabelWidth"
            prop="industry"
          >
            <el-input v-model="form.industry" autocomplete="off"></el-input>
          </el-form-item> -->
          <el-form-item label="所属部门" :label-width="formLabelWidth">
            <!-- <TreeSelct
              :props="{ value: 'id', label: 'name', children: 'children' }"
              :options="treeData"
              :accordion="true"
              :clearable="true"
              :value="division_id.toString()"
              :key="'TreeSelct' + division_id"
              ref="treeSelct"
              v-if="!treeDataLoading"
            /> -->
            {{ online_msg.division_name }}
          </el-form-item>

          <el-form-item label="客户所有人" :label-width="formLabelWidth">
            {{
              `${linkmanBelong.nickName}${
                linkmanBelong.realName ? "(" + linkmanBelong.realName + ")" : ""
              }`
            }}
          </el-form-item>
          <!-- <el-form-item
            label="客户级别"
            :label-width="formLabelWidth"
            prop="custom_level"
          >
            <el-select v-model="form.custom_level" placeholder="请选择客户级别">
              <el-option label="A(重点客户)" value="A"></el-option>
              <el-option label="B(普通客户)" value="B"></el-option>
              <el-option label="C(非优先客户)" value="C"></el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item
            label="客户等级"
            :label-width="formLabelWidth"
            prop="star_num"
          >
            <el-select
              v-model="form.star_num"
              placeholder="请选择客户等级"
              ref="star_num"
            >
              <el-option
                :label="' '"
                :value="index.toString()"
                v-for="index of 8"
                :key="index"
                ><i
                  style="color: #ece91f"
                  class="el-icon-star-on"
                  v-for="indexs of index"
                  :key="indexs"
                ></i
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="联系电话"
            :label-width="formLabelWidth"
            prop="phone"
          >
            <el-input v-model="form.phone" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item
            label="地址"
            :label-width="formLabelWidth"
            prop="address"
          >
            <el-input v-model="form.address" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item
            label="总人数"
            :label-width="formLabelWidth"
            prop="headcount"
          >
            <el-input v-model="form.headcount" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item
            label="省份"
            :label-width="formLabelWidth"
            prop="provinces"
          >
            <el-input v-model="form.provinces" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="城市" :label-width="formLabelWidth" prop="city">
            <el-input v-model="form.city" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="地区" :label-width="formLabelWidth" prop="area">
            <el-input v-model="form.area" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="备注"
            :label-width="formLabelWidth"
            prop="remark"
          >
            <el-input
              type="textarea"
              v-model="form.remark"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" v-loading="formLoading">
        <el-button @click="reset()" v-show="!edit_id">重置</el-button>
        <el-button type="primary" @click="submit('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="`跟进情况`"
      :visible.sync="followUpObj.visible"
      width="70%"
      top="10vh"
    >
      <div class="dialogCenter">
        <ChangeableTable
          :key="followUpObj.loading"
          ref="changeableTable"
          :tableColumn="followUpObj.changeColumn"
          :loading="followUpObj.loading || followUpObj.submitLoading"
          :dataProps="followUpObj.tableData"
          :tableConfig="{
            stripe: true,
            defaultSort: { prop: 'date', order: null },
          }"
          :slotArray="slotArray"
          @save="situationSave"
        >
          <div slot="附件" slot-scope="{ scopeRow, index }" class="slotPart">
            <ChangeableTable
              @saveAll="
                saveAll(
                  $event,
                  scopeRow.id ? { id: scopeRow.id } : { index: index }
                )
              "
              :mapping="{ fileName: 'filePath' }"
              :tableColumn="uploadColumn"
              :addTitle="`添加附件`"
              :slotArray="['下载']"
              :dataProps="
                scopeRow.attachment ? JSON.parse(scopeRow.attachment) : []
              "
            >
              <div slot="下载" slot-scope="{ scopeRow }">
                <span v-show="!scopeRow.filePath"> 暂无下载</span>
                <el-link
                  v-show="scopeRow.filePath"
                  type="success"
                  :href="uploadUrl(scopeRow.filePath, scopeRow.fileName)"
                  >下载附件</el-link
                >
              </div>
            </ChangeableTable>
          </div>
        </ChangeableTable>
      </div>
    </el-dialog>
    <el-dialog
      title="联系人"
      append-to-body
      :visible.sync="linkmanVisible"
      width="80%"
      top="5vh"
      @close="linkmanClose"
    >
      <div class="dialogCenter-other">
        <Linkman
          :multiSelect="true"
          ref="linkman"
          :linkmanSelList="gridData.data"
          :key="linkmanVisible"
          @editChecked="editChecked"
        ></Linkman>
      </div>
    </el-dialog>

    <el-dialog
      title="取出客户"
      append-to-body
      :visible.sync="transferData.show"
      width="50%"
      top="5vh"
      @closed="transferData.multipleBool = false"
      v-loading="transferData.formLoading"
    >
      <div style="height: 65vh; padding: 10px">
        <el-form
          :model="transferData.formData"
          ref="transferDataForm"
          :rules="transferData.rules"
        >
          <el-form-item label="审批部门" :label-width="formLabelWidth">
            <!-- <el-input v-model="transferData.formData.after_admins_id" autocomplete="off"></el-input> -->
            <!-- {{
              online_msg.division_pid
                ? online_msg.division_pid_name
                : "无需审批"
            }} -->
            <span v-show="needApproveText === false">无需审批</span>
            <span v-show="needApproveText !== false" style="color: #f56c6c">{{
              online_msg.division_pid_name
            }}</span>
          </el-form-item>

          <el-form-item
            label="备注"
            :label-width="formLabelWidth"
            prop="remark"
          >
            <el-input
              v-model="transferData.formData.remark"
              autocomplete="off"
              type="textarea"
              :autosize="{ minRows: 5 }"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="transferDataSubmit('transferDataForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
const gridDataColumn = [
  {
    dataIndex: "name",
    width: "220",
    title: "联系人姓名",
    returnField: "like-crm_linkman-name",
  },
  {
    dataIndex: "company_name",
    width: "220",
    title: "公司名称",
    returnField: "like-crm_linkman-company_name",
  },
  {
    dataIndex: "establish_date",
    width: "300",
    title: "成立日期",
    returnField: "like-crm_linkman-establish_date",
  },
  {
    dataIndex: "address",
    width: "300",
    title: "注册地址",
    returnField: "like-crm_linkman-address",
  },
  {
    dataIndex: "division_name",
    width: "220",
    title: "所属部门",
    returnField: "like-chain-division_name",
  },
  {
    scopedSlots: "nickName",
    width: "220",
    title: "联系人所有人",
    // returnField: "like-admins-nickName",
    manyField: ["like-admins-nickName", "like-admins-realName"],
  },
  {
    dataIndex: "dutuies",
    width: "220",
    title: "职务",
    returnField: "like-crm_linkman-dutuies",
  },
  {
    dataIndex: "phone",
    width: "220",
    title: "固定电话",
    returnField: "like-crm_linkman-phone",
  },
  // {
  //   scopedSlots: "crm_customer_id",
  //   // dataIndex: "crm_customer_id",
  //   width: "220",
  //   title: "所属客户(id)",
  //   returnField: "like-crm_customer-id",
  // },
  // {
  //   // dataIndex: "customer_company_name",
  //   scopedSlots: "customer_company_name",

  //   width: "220",
  //   title: "所属客户(公司名称)",
  //   returnField: "like-crm_customer-company_name",
  // },
  {
    scopedSlots: "sex",
    width: "220",
    title: "性别",
    dataType: "select",
    selectOptions: [
      {
        title: "男",
        value: 1,
      },
      {
        title: "女",
        value: 0,
      },
    ],
    returnField: "equal-crm_linkman-sex",
  },
  {
    dataIndex: "wechat_number",
    width: "220",
    title: "微信号",
    returnField: "like-crm_linkman-wechat_number",
  },
  {
    dataIndex: "contact_number",
    width: "220",
    title: "联系电话",
    returnField: "like-crm_linkman-contact_number",
  },
  {
    dataIndex: "email",
    width: "220",
    title: "邮件",
    returnField: "like-crm_linkman-email",
  },
  {
    dataIndex: "address",
    width: "220",
    title: "地址",
    returnField: "like-crm_linkman-address",
  },
  {
    dataIndex: "zipCode",
    width: "250",
    title: "邮编",
    returnField: "like-crm_linkman-zipCode",
  },
  {
    dataIndex: "provinces",
    width: "220",
    title: "省份",
    returnField: "like-crm_linkman-provinces",
  },
  {
    dataIndex: "remark",
    width: "250",
    title: "备注",
    returnField: "like-crm_linkman-remark",
  },
];

const tableColumn = [
  // {
  //   dataIndex: "id",
  //   width: "100",
  //   title: "ID",
  //   returnField: "like-crm_customer-id",
  // },

  {
    dataIndex: "pool_remark",
    width: "230",
    title: "转移备注",
    returnField: "like-crm_customer-pool_remark",
  },
  {
    dataIndex: "company_name",
    width: "400",
    title: "公司名称",
    returnField: "like-crm_customer-company_name",
  },
{
    dataIndex: "establish_date",
    width: "300",
    title: "成立日期",
    returnField: "like-crm_linkman-establish_date",
  },
  {
    dataIndex: "address",
    width: "300",
    title: "注册地址",
    returnField: "like-crm_linkman-address",
  },
  {
    dataIndex: "division_name",
    width: "220",
    title: "所属部门",
    returnField: "like-crm_customer-division_name",
  },
  {
    scopedSlots: "nickName",
    width: "220",
    title: "客户所有人",
    // returnField: "like-admins-nickName",
    manyField: ["like-admins-nickName", "like-admins-realName"],
  },
  {
    dataIndex: "wechat_number",
    width: "220",
    title: "微信号",
    returnField: "like-crm_linkman-wechat_number",
  },
  {
    dataIndex: "contact_number",
    width: "220",
    title: "联系电话",
    returnField: "like-crm_linkman-contact_number",
  },
  {
    dataIndex: "industry",
    width: "220",
    title: "行业",
    returnField: "like-crm_customer-industry",
  },
  {
    dataIndex: "phone",
    width: "220",
    title: "电话",
    returnField: "like-crm_customer-phone",
  },
  {
    scopedSlots: "star_num",
    width: "220",
    title: "客户等级",
    dataType: "selectNum",
    selectNum: 8,
    icon: "el-icon-star-on",
    color: "#ece91f",
    returnField: "equal-crm_customer-star_num",
  },
  {
    dataIndex: "address",
    width: "220",
    title: "地址",
    returnField: "like-crm_customer-address",
  },
  {
    dataIndex: "provinces",
    width: "220",
    title: "省份",
    returnField: "like-crm_customer-provinces",
  },
  {
    dataIndex: "city",
    width: "220",
    title: "市",
    returnField: "like-crm_customer-city",
  },
  {
    dataIndex: "area",
    width: "220",
    title: "区",
    returnField: "like-crm_customer-area",
  },
  {
    dataIndex: "remark",
    width: "250",
    title: "备注",
    returnField: "like-crm_linkman-remark",
  },
  {
    scopedSlots: "operation",
    width: "180",
    title: "操作",
    position: "right",
    noSearch: 1,
  },
  // { dataIndex: "remark", width: "250", title: "备注" },
];

const formOriginal = () => {
  return {
    linkman_id: null,
    company_name: null,
    division_id: null,
    // admins_id: null,
    industry: null,
    star_num: null,
     establish_date:null,
    // custom_level: null, //客户级别
    phone: null,
    address: null,
    sales: null,
    headcount: null,
    provinces: null,
    city: null,
    area: null,
    remark: null,
  };
};

const changeColumn = [
  {
    dataType: "date",
    title: "跟进日期",
    prop: "date",
    width: "250px",
    columnConfig: { sortable: true },
  },
  {
    dataType: "text",
    title: "跟进人",
    prop: "name",
    width: "200px",
  },
  {
    dataType: "text",
    title: "跟进状态",
    prop: "state",
    width: "120px",
  },
  {
    dataType: "textarea",
    title: "跟进描述",
    prop: "describe",
    width: "200px",
  },
];

const uploadColumn = [
  {
    dataType: "upload",
    title: "附件名称",
    prop: "fileName",
    width: "250px",
  },
  {
    dataType: "textarea",
    title: "附件备注",
    prop: "remark",
  },
];
const transferFormData = () => {
  return {
    customer: null,
    remark: "", //审批备注
    after_admins_id: null, //转移后id
    // after_division_id:null,
    update_time: null, //修改时间
  };
};
// import TreeSelct from "@/components/TreeSelct";
import TableGeneral from "@/components/TableGeneral";
import ChangeableTable from "@/components/ChangeableTable";
import Linkman from "@/components/Pages/Linkman";
import { mapActions, mapState } from "vuex";
export default {
  name: "ComplexTable",
  components: {
    // TreeSelct,
    TableGeneral,
    ChangeableTable,
    Linkman,
  },
  authorize: {
    transfer: "取出",
    delOne: "删除",
    edit: "编辑",
    followUp: "跟进情况",
  },
  data() {
    return {
      uploadColumn: uploadColumn,
      slotArray: ["附件"],
      gridData: {
        loading: false,
        data: [],
        gridDataColumn: gridDataColumn,
      },
      dialogFormVisible: false,
      form: formOriginal(),
      formLabelWidth: "120px",
      linkmanSelList: [],
      treeDataLoading: true,
      tableLoading: true,
      formLoading: false,
      division_id: 0,
      treeData: [],
      edit_id: 0,
      config: {
        pageSize: 20,
        page: 1,
        keyWord: {},
      },
      linkmanVisible: false,
      rules: {
        name: [
          { required: true, message: "姓名不为空", trigger: "blur" },
          { max: 255, message: "长度不超过255字符", trigger: "blur" },
        ],
        company_name: [
          { required: true, message: "公司名称不为空", trigger: "blur" },
          { max: 255, message: "长度不超过255字符", trigger: "blur" },
        ],
        // linkman_id: [
        //   { required: true, message: "联系人不为空", trigger: "blur" },
        // ],
      },
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      tableData: [],
      tableColumn: tableColumn,
      tableCount: 0,
      linkmanBelong: {},
      followUpObj: {
        visible: false,
        changeColumn: changeColumn,
        loading: false,
        submitLoading: false,
        tableData: [],
        target_id: "", //联系人id
        followUp_id: "", //沟通记录表id
        table_name: "crm_customer", //表名
        // total:0,
      },
      expandedRows: [],
      expandedRow: {},
      expandedRowsId: {},
      transferData: {
        formLoading: false,
        pidAdmins: [], //部门父级的admins
        show: false, //是否显示弹窗
        formData: transferFormData(),
        divisionOptional: [],
        divisionValue: "",
        divisionLoading: false,
        adminsList: [],
        adminsLoading: false,
        rightShow: false,
        clickAdminsId: "", //当前点中的admin id
        clickCustomer: {}, //当前点中的admin id
        rules: {
          after_admins_id: [
            { required: true, message: "请选择转移对象", trigger: "blur" },
          ],
        },
        multipleSelection: [],
        multipleBool: false, //批量操作时
      },
    };
  },
  created() {
    // this.divisionListLoad();
    this.tableLoad();
    this.division_id = this.online_msg.division_id;
  },
  watch: {
    "expandedRows.length": {
      async handler(newValue, oldValue) {
        if (newValue > oldValue && newValue != 0) {
          let id = this.expandedRow.id;
          let linkman_id = this.expandedRow.linkman_id;
          this.linkmanTableLoad(id, linkman_id);
        } // 展开行
      },
    },
    "form.star_num": {
      handler(newValue, oldValue) {
        // todo
        // console.log(newValue);
        // console.log(oldValue);
        if (newValue) {
          this.$refs.star_num.$el.children[0].setAttribute(
            "style",
            "position: relative"
          );
          let str = "";
          for (let i = 0; i < newValue; i++) {
            str += `<i
                     style="color: #ece91f"
                     class="el-icon-star-on" ></i>`;
          }
          let div = document.createElement("div"); //创建新标签
          div.innerHTML = str;
          div.style = "color:red;position: absolute;left:15px;top:0";
          let Vnode = this.$refs.star_num.$el.children[0].children[2];
          if (Vnode) {
            this.$refs.star_num.$el.children[0].removeChild(Vnode);
          }
          this.$refs.star_num.$el.children[0].appendChild(div);
        } else {
          let Vnode = this.$refs.star_num.$el.children[0].children[2];
          if (Vnode) {
            this.$refs.star_num.$el.children[0].removeChild(Vnode);
          }
        }
      },
    },
  },
  computed: {
    ...mapState("user", ["online_msg"]),
    needApproveText() {
      // if (
      //   this.transferData.formData.after_admins_id === 0 || //客户池
      //   !this.online_msg.division_pid || //没有父级
      //   this.transferData.divisionValue != this.online_msg.division_id || //选中的不为同级
      //   this.transferData.formData.after_admins_id == this.online_msg.id //子级选父级自己
      // ) {
      //   return false; //无需审批
      // } else {
      //   return true; //需要审批
      //   // this.online_msg.division_pid_name;
      // }
      if (
        this.transferData.clickCustomer.division_id ==  this.online_msg.division_id
      ) {
        return true;
      } else {
        return false;
      }
    },
  },
  methods: {
    ...mapActions("division", ["divisionList", "divisionOptional"]),
    ...mapActions("admins", ["adminsList"]),
    ...mapActions("linkman", ["linkmanGirdData"]),
    ...mapActions("followUp", [
      "crmFollowUpAdd",
      "crmFollowUpEdit",
      "crmFollowUpSelOne",
    ]),
    ...mapActions("customer", [
      "customerAdd",
      "customerEdit",
      "customerSelOne",
      "customerPool",
      "customerChange",
    ]),
    ...mapActions("situation", ["situationUpdateAdd", "situationList"]),
    async linkmanTableLoad(id, linkman_id) {
      delete this.expandedRowsId[id];
      let data = [];

      if (linkman_id) {
        let res = await this.linkmanGirdData({
          keyWord: {
            "in-crm_linkman-id": linkman_id,
          },
        });
        if (res.code == 200) {
          const { list } = res.data;
          data = list;
        }
      }
      this.$set(this.expandedRowsId, id, data);
    },
    async transfer(scopeRow) {
      //  let res = await this.situationUpdateAdd({ formData });
      this.transferData.show = true;

      // await this.divisionOptionalLoad();
      // this.transferData.divisionValue = null;
      this.transferData.formData = transferFormData();
      // this.transferData.rightShow = false;

      this.transferData.formData.after_admins_id = this.online_msg.id;
      if (scopeRow) {
        this.transferData.clickCustomer = scopeRow;

        this.transferData.formData.customer = scopeRow.id;
        this.transferData.formData.update_time = scopeRow.update_time;
      }

      // this.transferData.clickAdminsId = scopeRow.admins_id;
    },
    async situationSave(formData, index) {
      this.followUpObj.submitLoading = true;
      formData["table_name"] = this.followUpObj.table_name;
      formData["target_id"] = this.followUpObj.target_id;
      let res = await this.situationUpdateAdd({ formData });
      if (res.code == 200) {
        this.$message({
          message: formData.hasOwnProperty("delete_time")
            ? "删除成功"
            : "保存成功",
          type: "success",
        });
        if (res.data.id) {
          this.$refs.changeableTable.assignment(index, { id: res.data.id });
        }
        // this.followUp(this.followUpObj.target_id)
      }
      this.followUpObj.submitLoading = false;
    },
    closed() {
      this.edit_id = "";
      this.form = formOriginal();
      this.division_id = this.online_msg.division_id;
      // this.$refs.treeSelct.reset();
      this.linkmanSelList = [];
      this.gridData.data = [];
      this.$refs.form.clearValidate();
    },
    addShow() {
      // e.preventDefault()
      this.linkmanBelong = {
        nickName: this.online_msg.nickName,
        realName: this.online_msg.realName,
      };
      this.dialogFormVisible = true;
    },
    reset() {
      this.form = formOriginal();
      // this.$refs.treeSelct.reset();
      this.linkmanSelList = [];
      this.gridData.data = [];
    },
    async tableLoad() {
      this.tableLoading = true;
      let res = await this.customerPool(
        // division_id: this.online_msg.division_id,
        this.config
      );
      if (res.code == 200) {
        const { list, total } = res.data;
        this.tableData = list;
        this.tableCount = total;
      }
      this.tableLoading = false;
    },

    search(e) {
      //  console.log(e)
      this.config.keyWord = e;
      this.tableLoad();
    },

    async edit(scopeRow) {
      this.dialogFormVisible = true;
      this.formLoading = true;
      this.edit_id = scopeRow.id;
      let res = await this.customerSelOne({ id: scopeRow.id });
      if (res.code == 200) {
        Object.keys(formOriginal()).forEach(
          (item) => (this.form[item] = res.data[item])
        );
        this.division_id = this.form.division_id;
        // this.form.linkman_id = this.form.linkman_id
        //   ? this.form.linkman_id.split(",").map((item) => Number(item))
        //   : null;

        if (this.form.linkman_id) {
          this.linkmanSelList = this.form.linkman_id.split(",");
        }
        // this.linkmanSelList = this.form.linkman_id   ? this.form.linkman_id.split(",").map((item) => Number(item))  : null;

        this.linkmanBelong = {
          nickName: scopeRow.nickName,
          realName: scopeRow.realName,
        };

        this.formLoading = false;
      }
    },
    async delOne(id) {
      this.tableLoading = true;
      let res = await this.customerEdit({
        formData: { delete_time: this.sysTime() },
        conditions: { id: id },
      });
      if (res.code == 200) {
        this.$message.success("删除成功");
      }
      this.tableLoad();
    },

    async followUp(id) {
      this.followUpObj.visible = true;
      this.followUpObj.loading = true;
      this.followUpObj.target_id = id;
      // if (scopeRow.followUp_id) {
      let res = await this.situationList({
        keyWord: {
          "equal-crm_situation-target_id": id,
          "equal-crm_situation-table_name": this.followUpObj.table_name,
        },
      });
      if (res.code == 200) {
        const { list } = res.data;
        this.followUpObj.tableData = list;
        // this.followUpObj.total = total
      }
      // } else {
      //   this.followUpObj.tableData = [];
      // }
      // console.log( this.followUpObj.tableData)
      this.followUpObj.loading = false;
    },
    submit(formName) {
      this.form.linkman_id =
        this.linkmanSelList.length > 0 ? this.linkmanSelList.join(",") : null;

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm(
            "确定要" + (this.edit_id ? "编辑" : "添加") + "吗?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              this.formLoading = true;

              if (!this.edit_id) {
                this.form.admins_id = this.online_msg.id;
                this.form.division_id = this.online_msg.division_id;
              }

              let form = this.form;
              if (this.edit_id) {
                delete form.admins_id;
                var res = await this.customerEdit({
                  formData: form,
                  conditions: { id: this.edit_id },
                });
              } else {
                var res = await this.customerAdd({ formData: form });
              }
              if (res.code == 200) {
                this.$message.success(res.message);
                this.dialogFormVisible = false;
                this.tableLoad();
                //  this.linkmanTableLoad(this.edit_id,form.linkman_id)
                this.expandedRows = [];
              }
              this.formLoading = false;
            })
            .catch(() => {});
        } else {
          // console.log('error submit!!');
          this.$message.error("信息填写错误");
          return false;
        }
      });
    },
    transferDataSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert("submit!");
          //          return {
          //   customer_id: null,
          //   remark: null, //审批备注
          //   after_admins_id: null, //转移后id
          //   update_time: null, //修改时间
          // };
          this.$confirm("确定要取出吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(async () => {
            this.transferData.formLoading = true;
            let formData = {
              ...this.transferData.formData,
              after_division_id: this.online_msg.division_id,
              before_admins_id: 0,
              division_id:this.needApproveText === false ? 0 : this.online_msg.division_pid,
            };
            if (this.transferData.multipleBool) {
              formData.customer = this.transferData.multipleSelection;
            }
            let res = await this.customerChange(formData);
            if (res.code == 200) {
              this.$message({
                message: res.message,
                type: "success",
              });
            }
            this.transferData.formLoading = false;
            this.transferData.show = false;
            this.tableLoad();

            // Request::has('customer_id') && Request::has('remark') &&  Request::has('after_admins_id') && Request::has('update_time') && Request::has('division_id')
          });
        }
      });
    },
    currentChange(e) {
      this.config.page = e;
      this.tableLoad();
    },
    sizeChange(e) {
      this.config.pageSize = e;
      this.tableLoad();
    },
    sexShow(sex) {
      if (sex == null || sex == "") {
        return "未知";
      } else {
        return sex == 1 ? "男" : "女";
      }
    },
    async divisionOptionalLoad() {
      this.transferData.divisionLoading = true;
      let res = await this.divisionOptional();
      if (res.code == 200) {
        this.transferData.divisionOptional = res.data.list;
      }
      this.transferData.divisionLoading = false;
    },
    // async divisionListLoad() {
    //   this.treeDataLoading = true;
    //   let res = await this.divisionList({ "equal-crm_division-status": 1 });
    //   if (res.code == 200) {
    //     this.treeData[0] = { name: "全公司", id: 0, children: [] };
    //     this.treeData[0].children = res.data.list;
    //     this.treeDataLoading = false;
    //   }
    // },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    divisionChange(e) {
      // console.log(e)
      // this.$refs.transferDataForm.clearValidate()
      // if (e === 0) {
      //   this.transferData.rightShow = false;
      //   this.transferData.formData.after_admins_id = 0;
      // } else {
      this.transferData.rightShow = true;
      this.transferData.formData.after_admins_id = null;
      this.adminsListLoad(e);
      // }
    },

    async adminsListLoad(e) {
      this.transferData.adminsLoading = true;
      let res = await this.adminsList({
        keyWord: { "equal-admins-division_id": e },
      });
      if (res.code == 200) {
        this.transferData.adminsList = res.data.list;
      }
      // this.transferData.adminsList.unshift({ id: 0, nickName: "客户池" });

      this.transferData.adminsLoading = false;
    },

    async showInput() {
      await this.linkmanListLoad();

      this.linkmanVisible = true;
    },
    editChecked(linkmanSelList) {
      this.linkmanSelList = linkmanSelList;
      this.linkmanListLoad();
    },

    async linkmanListLoad() {
      this.gridData.loading = true;
      if (this.linkmanSelList.length > 0) {
        let res = await this.linkmanGirdData({
          keyWord: {
            "in-crm_linkman-id": this.linkmanSelList.join(","),
          },
        });
        if (res.code == 200) {
          const { list } = res.data;
          this.gridData.data = list;
        }
      } else {
        this.gridData.data = [];
      }

      this.gridData.loading = false;
    },

    linkmanClose(e) {
      this.linkmanSelList = this.$refs.linkman.returnSelArray();
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    async saveAll(data, obj) {
      this.followUpObj.submitLoading = true;
      let dataJson = JSON.stringify(data);
      if (obj.hasOwnProperty("id")) {
        var res = await this.situationUpdateAdd({
          formData: { attachment: dataJson, id: obj.id },
        });
        if (res.code == 200) {
          this.$message.success("保存成功");
        }
      } else if (obj.hasOwnProperty("index")) {
        // console.log(obj);
        // console.log({ attachment: dataJson });
        this.$refs.changeableTable.assignment(obj.index, {
          attachment: dataJson,
        });
      }
      this.followUpObj.submitLoading = false;
    },
    takeOut(row) {
      // if(row.division_id == this.online_msg.division_id){  //如果取出的是同级的客户
      // }else{
      // }
    },
    expandChange(row, expandedRows) {
      //  console.log(row)
      //  console.log(expandedRows)
      this.expandedRow = row;
      this.expandedRows = expandedRows;
    },
    async manyChange() {
      let multipleSelection = this.$refs.general.multipleSelection;

      if (multipleSelection.length > 0) {
        this.transferData.multipleSelection = multipleSelection;
        this.transferData.multipleBool = true; //开启批量功能
        this.transfer();

        // this.$confirm("确定要修改吗?", "提示", {
        //   confirmButtonText: "确定",
        //   cancelButtonText: "取消",
        //   type: "warning",
        // }).then(async () => {

        // });
      } else {
        this.$message({
          type: "error",
          message: "请选择审批对象",
        });
      }
    },
  },
};
</script>
<style scoped lang="less">
.dialogCenter-other {
  height: 75vh;
  overflow-y: scroll;
  padding: 10px;
}
.dialogCenter {
  height: 65vh;
  overflow-y: scroll;
  padding: 10px;
}
.pagination {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.item {
  margin-right: 20px;
}
.linkman-part {
  display: flex;
  align-items: center;
}
.gridDataTable {
  max-height: 50vh;
  overflow-y: auto;
}
.slotPart {
  // width:100%;
  margin-bottom: 20px;
  margin-top: 20px;
  // width: 600px;
}
.tableGeneral {
  width: 28%;
  //  display: flex;
  border: 1px solid rgb(218, 214, 214);
  z-index: 0;
}
.company_name-part{
  display: flex;
}
</style>
